<?php

namespace app\admin\controller;
use think\Db;
use app\common\controller\Backend;

/**
 * 用户订单
 *
 * @icon fa fa-circle-o
 */
class Order extends Backend
{
    
    /**
     * Order模型对象
     * @var \app\admin\model\Order
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\Order;
        $this->view->assign("orderSourceList", $this->model->getOrderSourceList());
        $this->view->assign("orderTypeList", $this->model->getOrderTypeList());
        $this->view->assign("orderStatusList", $this->model->getOrderStatusList());
    }
    
    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */
    

    /**
     * 查看
     */
    public function index()
    {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax())
        {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField'))
            {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            $total = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where('order_type',1)
                    ->order($sort, $order)
                    ->count();

            $list = $this->model
                    ->with(['user'])
                    ->where($where)
                    ->where('order_type',1)
                    ->order($sort, $order)
                    ->limit($offset, $limit)
                    ->select();
   
            // foreach ($list as $row) {
            //     if($row->pay_account){
            //         $pay_account =Db::name('user')->where('id',$row->user_id)->value($row->pay_account);
            //         if($row->pay_account=='wechatpay'){
            //             $row->account_type ='微信';
            //             $pay_account = json_decode($pay_account,true);
            //             $row->account_name = isset($pay_account['account_name'])?$pay_account['account_name']:'';
            //             $row->account_number =isset($pay_account['account_number'])?$pay_account['account_number']:'';
            //             $row->account_image =isset($pay_account['account_image'])?$pay_account['account_image']:'';
            //         }

            //         if($row->pay_account=='alipay'){
            //             $row->account_type ='支付宝';
            //             $pay_account = json_decode($pay_account,true);
            //             $row->account_name = isset($pay_account['account_name'])?$pay_account['account_name']:'';
            //             $row->account_number =isset($pay_account['account_number'])?$pay_account['account_number']:'';
            //             $row->account_image =isset($pay_account['account_image'])?$pay_account['account_image']:'';
            //         }

            //         if($row->pay_account=='bankpay'){
            //             $row->account_type ='银行卡';
            //             $pay_account = json_decode($pay_account,true);
            //             $account_bank_name = isset($pay_account['account_bank_name'])?$pay_account['account_bank_name']:'';
            //             $row->account_name = isset($pay_account['account_name'])?$pay_account['account_name']:'';
            //             $row->account_number =isset($pay_account['account_number'])?$pay_account['account_number']:'';
            //         }
                    
            //     }else{
            //         $row->pay_account = '无';
            //     }
                
                
            // }
            $list = collection($list)->toArray();
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    public function rebut($ids=null){
        $row = Db::name('user_order')
        ->where(['id'=>$ids,'order_source'=>1,'order_type'=>1,'order_status'=>0])
        ->find();
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        Db::startTrans();
        try {
            Db::name('user_order')
            ->where(['id'=>$ids])
            ->update(['order_status'=>3]);

            Db::name('user')
            ->where(['id'=>$row['user_id']])
            ->update([
            'fil_wallet' => Db::raw('fil_wallet+'.$row['fil']),
            ]);
            $findUser = Db::name('user')
            ->where(['id'=>$row['user_id']])
            ->find();
            $user_balance_log['user_id']    = $row['user_id'];
            $user_balance_log['amount']     = $row['fil'];
            $user_balance_log['before']     = $findUser['fil_wallet'];
            $user_balance_log['after']      = $findUser['fil_wallet']+$row['fil'];
            $user_balance_log['remark']     = 'OTC订单卖出驳回';
            $user_balance_log['type']       = 1;
            $user_balance_log['log_type']   = 8;
            $user_balance_log['createtime'] = time();
            Db::name('user_balance_log')->insert($user_balance_log);
            Db::commit();
            $this->success('驳回成功');
        } catch (PDOException $e) {
            Db::rollback();
            $this->error($e->getMessage());
        } catch (Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }

    }

    //FIL提币通过
    public function agree($ids=null){
        $order = Db::name('user_order')->where('id',$ids)->find();
        if($order['order_status'] != 0){
            $this->error('订单已审核');
        }
        $data['coin_value'] = $order['fil'] - $order['transfer_fee'];
        if($data['coin_value'] < 0){
            $this->error('提币金额太小');
        }
        $data['address'] = $order['address'];
        $data['object_id'] = 1;
        $data['saas_id'] = 'bitstart';
        $Http = new \fast\Http;
        $url = 'http://eth.abxx.im/api/coin/Wallet/handle_transfer_accounts?accessToken=1c12e6761ae23rsd1234c83d201a667422529c9f0c12e5f895a83640d2ddb==&coinType=fil3';
        $json = $Http::post($url,$data);
        $return = json_decode($json,true);
        if($return['code'] == 0){
            $this->error('提币失败请联系客服');
        }else{
            // 启动事务
            Db::startTrans();
            try{
                $res = Db::name('user')->where('id',$order['user_id'])->setDec('fil_wallet',$data['coin_value']);
                //改变订单状态
                $res = Db::name('user_order')->where('id',$ids)->setField('order_status',4);
                // 提交事务
                Db::commit();
                $this->success('提币成功');
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->error($e->getMessage());
//                $this->error('提币失败');
            }
        }
    }

    //FIL3提币驳回
    public function disagree($ids=null){
        $order = Db::name('user_order')->where('id',$ids)->find();
        if($order['order_status'] == 3){
            $this->error('已经驳回');
        }
        $res = Db::name('user_order')->where('id',$ids)->setField('order_status',3);
        if($res){
            $this->success('驳回成功');
        }else{
            $this->error('驳回失败');
        }
    }

}
